package com.zl.learning.xml.test;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;

public class DOMStudentInfo {  
  
    /** 
     * @param args 
     */  
    public static void main(String[] args) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
        try {  
            DocumentBuilder db = dbf.newDocumentBuilder();  
            Document doc = db.parse(new File("students.xml"));  
            NodeList nl = doc.getElementsByTagName("student");  
            int len = nl.getLength();  
            for(int i=0;i<len;i++){  
                Element eltStu = (Element)nl.item(i);  
                Node eltName = eltStu.getElementsByTagName("name").item(0);  
                Node eltAge = eltStu.getElementsByTagName("age").item(0);  
                //注意:此时不能用eltName.getNodeValue()得到“张三”的值  
                //因为"张三"这个文本节点是name的子节点,所以得调用  
                //eltName.getFirstChild().getNodeValue()来得到"张三"的值  
                System.out.println("name:"+eltName.getFirstChild().getNodeValue());  
                System.out.println("age:"+eltAge.getFirstChild().getNodeValue());  
            }  
        } catch (ParserConfigurationException e) {  
            e.printStackTrace();  
        } catch (SAXException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
          
    }  
  
}  